<?php

namespace App\Services\WeChat;

use App\Models\Temp;
use Illuminate\Support\Arr;

class MessageDispatcher
{
    public function send(string $type, string $openid, array $data)
    {
        // 1. 获取策略类
        $strategyClass = config("wechat_messages.mappings.{$type}");

        if (!$strategyClass || !class_exists($strategyClass)) {
            throw new \InvalidArgumentException("Unsupported message type: {$type}");
        }

        // 2. 获取模板ID

        $template = Temp::query()->where('id',$data['temp_id'])->first();
        if($type == 'mini') {
            $templateId = $template->mini_template_id
                ?? $data['template_id'];
        }else{
            $templateId = $template->template_id
                ?? $data['template_id'];
        }

        if (!$templateId) {
            throw new \InvalidArgumentException("Missing template ID for type: {$type}");
        }

        // 3. 实例化策略并发送
        $strategy = app($strategyClass);
        return $strategy->send($openid, $data, $templateId);
    }
}
